<template>
  <ry-modal :title="`${title}会员卡`" v-model="visible" destroyOnClose :maskClosable="false"
    :confirmLoading="confirmLoading" @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <a-form-model :model="form" :rules="rules" v-bind="modelConfig">
        <a-row :gutter="[24,0]">
          <a-col :span="24" style="font-weight: 600;margin-bottom: 10px;margin-left: 20px">
            <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>会员卡信息
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="会员卡名称" prop="cardName">
              <a-input v-model="form.cardName" placeholder="请输入会员卡名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="限制数量" prop="limitedQuantity">
              <a-input-number v-model="form.limitedQuantity" placeholder="数量" /><span> 张</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="产品总价值" prop="totalPrice">
              <a-input-number v-model="form.totalPrice" placeholder="金额" /><span> 万/年</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="会员活动价" prop="activityPrice">
              <a-input-number v-model="form.activityPrice" placeholder="金额" :min="0" /><span> 万/年</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-col :span="24" style="font-weight: 600;margin-bottom: 20px;margin-left: 20px">
              <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>会员卡信息
            </a-col>
            <a-button class="editable-add-btn" type="primary" @click="handleAdd">
              新增
            </a-button>
            <a-table bordered :data-source="projects" :columns="columns">
              <template slot="projectName" slot-scope="text, record">
                <ry-select
                  :data-source="$getDict('APPLY_PROJECT')"
                  placeholder="请选择项目"
                  v-model="record.projectName">
                </ry-select>
              </template>
              <template slot="projectPrice" slot-scope="text, record">
                <a-input-number v-model="record.projectPrice" @change="updateTotalPrice" :min="0" /> 元
              </template>
              <template slot="quantity" slot-scope="text, record">
                <a-input-number v-model="record.quantity" @change="updateTotalPrice" :min="0" />
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  v-if="projects.length"
                  title="确认删除?"
                  @confirm="() => onDelete(record.indexKey)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </ry-modal>
</template>

<script>
import { CommonModal } from '@/ryweb'
export default {
  name: '',
  mixins: [CommonModal],
  props: ['url'],
  components: {  },
  data () {
    return {
      count: 0,
      form: {
      },
      projects: [],
      modelConfig: {
        ref: 'ruleForm',
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      columns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '30%',
          scopedSlots: { customRender: 'projectName' },
        },
        {
          title: '单价',
          dataIndex: 'projectPrice',
          width: '30%',
          scopedSlots: { customRender: 'projectPrice' },
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: '30%',
          scopedSlots: { customRender: 'quantity' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      rules: {
        limitedQuantity: [{
          required: true,
          message: '请输入身份证号码',
          trigger: 'blur'
        }],
        cardName: [{
          required: true,
          message: '请输入会员卡名称',
          trigger: 'blur'
        }],
        totalPrice: [{
          required: true,
          message: '请输入金额',
          trigger: 'blur'
        }],
        activityPrice: [{
          required: true,
          message: '请输入金额',
          trigger: 'blur'
        }]
      }
    }
  },
  created () {

  },
  computed: {

  },
  watch: {

  },
  methods: {
    add(record){
      this.title = '添加'
      this.form = { ...record }
      this.type = '1'
      this.visible = true
      this.projects = []
    },
    edit (record) {
      this.title = '修改'
      this.form = {...record}
      this.type = '2'
      this.visible = true
      this.projects = JSON.parse(JSON.stringify(record.projects))
    },
    onDelete(indexKey) {
      const projects = [...this.projects];
      this.projects = projects.filter(item => item.indexKey !== indexKey);
      this.updateTotalPrice(); // 更新总价
    },
    handleAdd () {
      const { count, projects } = this;
      const newData = {
        indexKey: count,
        projectName: '',
        projectPrice: 0,
        quantity: 0,
      };
      this.projects = [...projects, newData];
      this.count = count + 1;
      console.log(this.projects)
    },
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let whetherTrue = false
          this.projects.forEach(item => {
            if (item.projectName === '' || item.projectPrice === 0 || item.quantity === 0) {
              whetherTrue = true
            }
          })
          if (whetherTrue) {
            this.$message.error('项目名称必须选择,单价和数量不能为0')
            return
          }
          this.confirmLoading = true
          let params = { ...this.form }
          params.projects = this.projects
          const url = this.type === '1' ? this.url.add : this.url.edit
          this.$post(url, params).then(res => {
            this.confirmLoading = false
            if (res.code === 200) {
              this.$message.success('成功')
              this.visible = false
              this.$emit('ok')
            } else {
              this.$message.error('请求失败')
            }
          })
        } else {
          return false
        }
      })
    },
    updateTotalPrice () {
      // 计算所有项目价格的总和
      if (this.projects && this.projects.length > 0) {
        const total = this.projects.reduce((sum, project) => {
          // 计算每个项目的总价：单价 * 数量
          const projectTotal = (project.projectPrice || 0) * (project.quantity || 0);
          return sum + projectTotal;
        }, 0);
        // 更新表单中的totalPrice值
        this.$set(this.form, 'totalPrice', total / 10000)
      } else {
        this.form.totalPrice = 0;
      }
    },
  },
  mounted () {
  }
}
</script>

<style scoped>
.ry-modal .body-container .ant-form-item {
  margin-bottom: 0.15rem;
}
.editable-add-btn {
  margin-bottom: 8px;
}
</style>
